# -*- coding: utf-8 -*-

from wbhttp import HttpClient
from logger import logger
from model import WeiboFans

'''
    UID的所有评论用户
'''


class WeiboCommentUser(object):
    ## 获取某个用户的评论用户
    def get_ones_fans(self, uid):
        alluser = set([])
        url = 'https://m.weibo.cn/api/container/getIndex?uid=%s&luicode=20000174&featurecode=20000320&type=uid&value=%s&containerid=1076033194506490&page=0' % (
            uid, uid)
        headers = {
            'Referer': 'https://m.weibo.cn/u/%s' % uid
        }
        resp = HttpClient.get(url, headers)
        if resp.status_code == 200 and resp.json()['ok'] == 1:
            cards = resp.json()['data']['cards']
            for card in cards:
                mid = card['mblog']['id']
                alluser = alluser | self.get_comment_users(mid, uid)
        return alluser

    ## 获取某条微博的评论者
    def get_comment_users(self, wid, uid=None):
        headers = {
            'Referer': 'https://m.weibo.cn/status/' + str(wid)
        }
        fanses = set([])
        page = 0
        while True:
            url = "https://m.weibo.cn/api/comments/show?id=" + str(wid) + "&page=" + str(page)
            resp = HttpClient.get(url, headers)
            if resp.status_code == 200 and resp.json()['ok'] == 1:
                users = resp.json()['data']['data']
                for user in users:
                    u = user['user']
                    if u['id'] != uid:
                        fans = WeiboFans(u['id'], u['screen_name'], u['profile_image_url'], u['verified'],
                                         u['profile_url'])
                        fanses.add(fans)
                page = page + 1
            elif resp.status_code == 200 and resp.json()['ok'] == 0:
                logger.info(u'这条微博总共找到 %d 个评论者' % len(fanses))
                break
            else:
                logger.info(resp.json()['msg'])
                break
        return fanses

    ## 获取某个用户的第一条微博
    def get_fans_first_post(self, uid):
        url = 'https://m.weibo.cn/api/container/getIndex?uid=%s&type=uid&value=%s&page=0' % (
            uid, uid)
        headers = {
            'Referer': 'https://m.weibo.cn/u/%s' % uid
        }
        resp = HttpClient.get(url, headers)
        if resp.status_code == 200 and resp.json()['ok'] == 1:
            menus = resp.json()['data']['userInfo']['toolbar_menus']
            for menu in menus:
                if menu['type'] == 'toolbar_menu_list':
                    scheme = menu['params']['menu_list'][0]['scheme']

        if scheme != None:
            url = scheme.replace('m.weibo.cn/p/index', 'm.weibo.cn/api/container/getIndex')

        resp = HttpClient.get(url, headers)
        if resp.status_code == 200 and len(resp.json()['data']['cards']) > 0:
            cards = resp.json()['data']['cards']
            for card in cards:
                if card['card_type'] == 9:
                    return card['mblog']['id']
        return None
